package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.mapper.CommentMapper;
import com.example.blog.pojo.Comment;
import com.example.blog.pojo.Result;
import com.example.blog.service.CommentService;
import com.example.blog.util.TokenUtil.decryptToken;
import com.example.blog.util.TokenUtil.spiltUtils;
import com.example.blog.util.UserUtils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private UserUtils userIdUtil;


    @Override
    public Result<T> saveComment(Comment comment, int id, String token) {
        String pe = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(pe);
        Integer userId = userIdUtil.getUserId(userName);
        String nickname = userIdUtil.getNickname(userName);
        String headerUrl = userIdUtil.getHeaderUrl(userName);
        comment.setArticleId(id);
        comment.setUserId(userId);
        comment.setNickname(nickname);
        comment.setHeaderurl(headerUrl);
        comment.setParentId(0L);
        comment.setCreateTime(new Date());
        int insert = commentMapper.insert(comment);
        if (insert > 0) {
            return Result.success("评论成功！");
        }
        return Result.failed("评论失败！");
    }

    @Override
    public Result<List<Comment>> getComment(int id) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", id).orderByDesc("create_time");
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return Result.success(comments);
    }

    @Override
    public Result<List<Comment>> getNewComment() {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time").last("LIMIT 5"); // 按评论时间降序排列
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return Result.success(comments);
    }

}
